package top.saycode.schedule.base.model;

import top.saycode.schedule.base.common.Show;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public abstract class LiteDO {

    private final Map<Field, Integer> fieldLenMap;

    public LiteDO() {
        Class<? extends LiteDO> clazz = this.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        fieldLenMap = new HashMap<>();
        for (Field field : declaredFields) {
            int len = field.getName().length();
            fieldLenMap.put(field, Math.max(len, 6));
        }
    }

    protected Map<Field, Integer> getFieldLenMap(){
        return this.fieldLenMap;
    }

    public String show() {
        StringBuilder showBuilder = new StringBuilder();
        this.fieldLenMap.keySet().forEach(field -> {

            try {
                showBuilder.append(field.getName()).append(": ").append(field.get(this)).append("\n");
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
        showBuilder.append("-------------------------");
        return showBuilder.toString();
    }

    public String showTitle() {
        StringBuilder showBuilder = new StringBuilder();

        this.fieldLenMap.keySet().forEach(field -> {

            Show show = field.getAnnotation(Show.class);
            if (show != null && !show.value()) {
                return;
            }

            Integer len = fieldLenMap.get(field);
            String formatter = "%-" + len + "s ";
            showBuilder.append(formatter.formatted(field.getName()));
        });
        return showBuilder.toString();
    }

    public String showByListType(){
        StringBuilder showBuilder = new StringBuilder();

        this.fieldLenMap.keySet().forEach(field -> {

            Show show = field.getAnnotation(Show.class);
            if (show != null && !show.value()) {
                return;
            }

            Integer len = fieldLenMap.get(field);
            String formatter = "%-" + len + "s ";
            try {
                showBuilder.append(formatter.formatted(field.get(this)));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
        return showBuilder.toString();
    }
}
